package com.project.basis.core

import android.text.TextUtils
import com.project.basis.config.ProjectApplication.Companion.isLogin
import com.project.basis.config.ProjectApplication.Companion.loginEntity
import okhttp3.FormBody
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import org.json.JSONObject
import java.io.File

object CoreDataHandlerKt {

    // Post请求
    fun getPostBuilder(): FormBody.Builder {
        val builder = FormBody.Builder()
        if (isLogin()) {
            builder.add("uid", loginEntity!!.id)
        }
        return builder
    }

    // Get请求
    fun getGetBuilder(url: String): HttpUrl.Builder {
        val builder = url.toHttpUrl().newBuilder()
        if (isLogin()) {
            builder.addQueryParameter("uid", loginEntity!!.id)
        }
        return builder
    }

    // 上传文件请求
    fun getMultipartBuilder(): MultipartBody.Builder {
        val builder = MultipartBody.Builder()
        if (isLogin()) {
            builder.addFormDataPart("uid", loginEntity!!.id)
        }
        return builder
    }

    // 添加文件参数
    private fun addFileParameter(
        builder: MultipartBody.Builder,
        key: String,
        filePath: String
    ) {
        if (!TextUtils.isEmpty(filePath)) {
            val file = File(filePath)
            builder.addFormDataPart(
                key, file.name,
                file.asRequestBody("application/octet-stream".toMediaTypeOrNull())
            )
        }
    }

    // JSONObject
    fun getJsonObject(json: String? = null): JSONObject {
        var jsonObject = if (json != null) {
            JSONObject(json)
        } else {
            JSONObject()
        }
        if (isLogin()) {
            jsonObject.put("uid", loginEntity!!.id)
        }
        return jsonObject
    }

    fun getTikTokList(): HttpUrl {
        val builder = ServerHttpUrl.TEST_URL.toHttpUrl().newBuilder()
        builder.addQueryParameter("pageSize", "20")
        builder.addQueryParameter("page", "1")
        builder.addQueryParameter(
            "_signature",
            "_02B4Z6wo00101rib77wAAIDBCGoDdztUP-q4n-sAAM6RdN4cC8YUVjY8aWSpB4cVKmUrv-Fsn-O3Ugme.JrHS52IL38fXuLdeUZ4NgHfR1pLnpu0-j29m0IyKCvd3f6bDY3x8AWNDEusBnJZd9"
        )
        return builder.build()
    }
}